package com.huabo.sql.record;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huabo.utils.FastJsonUtils;

/**
 * 对应postgresql的jsonb数据类型
 * Created by Jackie Liu on 2017/9/28.
 */
public class JSONB implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private String data;
    private JSONObject json;

    public JSONB(String value) {
        this.data = value;
    }
    
    @SuppressWarnings("rawtypes")
    public JSONB(Map value) {
        this.data = FastJsonUtils.objToJson(value);
    }
    
    @SuppressWarnings("rawtypes")
	public JSONB(Collection value) {
    	this.data = FastJsonUtils.objToJson(value);
    }

    public JSONObject getJson() {
        if (StringUtils.isBlank(data)) {
            return null;
        }
        if (json == null) {
            json = JSON.parseObject(data);
        }
        return json;
    }

    public Object getProperty(String key) {
        getJson();
        if (json == null) {
            return null;
        }
        return json.get(key);
    }

    @Override
    public String toString() {
        return data;
    }
}
